<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\model\Materials;
use think\exception\ValidateException;
use think\response\Json;

class Material extends BaseController
{
    public function index()
    {
        $this->checkLogin();
        $key = $this->request->get('key');
        $material_list = Materials::with(['category', 'cover_info'])
            ->where('name|material_id', 'like', "%${key}%")
            ->order('create_time', 'desc')
            ->paginate(50);
        return $this->success('success', $material_list);
    }

    public function read($id = 0)
    {
        $this->checkLogin();
        $material = Materials::with(['category', 'warehouse', 'cover_info'])->find($id);
        if (empty($material)) return $this->error('物品不存在');
        return $this->success('success', $material);
    }

    public function save()
    {
        $this->checkLogin();
        if (!$this->auth->check('add_material', $this->user->id)) return $this->error('权限不足');
        $data = $this->request->post(['name', 'category_id', 'cover',
            'unit', 'specs', 'total', 'bar_code', 'notes']);
        try {
            $this->validate($data, \app\validate\Material::class);
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        }
        $data['material_id'] = getMaterialId();
        $material = Materials::create($data);
        return $this->success('物品添加成功', $material);
    }

    public function update($id): Json
    {
        $this->checkLogin();
        if (!$this->auth->check('edit_material', $this->user->id)) return $this->error('权限不足');
        $data = $this->request->post(['name', 'category_id', 'cover',
            'unit', 'specs', 'price', 'total', 'total', 'material_id', 'bar_code', 'notes']);
        try {
            $this->validate($data, \app\validate\Material::class);
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        }

        $material = Materials::find($id);
        if (empty($material)) return $this->error('物品不存在');

        $material->save($data);

        return $this->success('物品编辑成功', $material);
    }

    public function delete($id = 0)
    {
        $this->checkLogin();
        if (!$this->auth->check('delete_material', $this->user->id)) return $this->error('权限不足');
        Materials::destroy($id);
        return $this->success('success');
    }

    public function get_material_id()
    {
        return $this->success('success', getMaterialId());
    }
}
